package com.molichuxing.services.infrastructure.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.CollectionUtils;
import com.molichuxing.framework.utils.MapObjectConvertUtil;
import com.molichuxing.framework.utils.RedisUtil;
import com.molichuxing.framework.utils.StringUtil;
import com.molichuxing.services.infrastructure.dto.request.create.IovCreateAccountDto;
import com.molichuxing.services.infrastructure.dto.request.create.IovCreateGroupDto;
import com.molichuxing.services.infrastructure.dto.request.modify.IovModifyAccountDto;
import com.molichuxing.services.infrastructure.dto.request.modify.IovModifyGroupDto;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.IovPermissionService;
import com.molichuxing.services.util.IovPropertyUtils;
import com.molichuxing.services.util.IovUtils;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuruifeng
 * 车联网权限服务
 * 2019-10-12
 */
@Service("iovPermissionService")
public class IovPermissionServiceImpl implements IovPermissionService {
    private static final Logger logger = LoggerFactory.getLogger(IovPermissionServiceImpl.class);

    @Value("${iov.permission.url}")
    private String url;
    @Value("${iov.permission.appid}")
    private String appid;
    @Value("${iov.permission.secret}")
    private String secret;
    @Value("${iov.permission.grant_type}")
    private String grantType;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IovUtils iovUtils;


    /**
     * 车辆网创建用户接口
     *
     * @param account
     * @return
     */
    @Override
    public ResponseResult<Boolean> createAccount(IovCreateAccountDto account) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (account == null)
            return result.error("参数不能为空", Boolean.FALSE);

        Map<String, Object> paramMap = MapObjectConvertUtil.objectToMap(account);
        if (paramMap != null && paramMap.size() > 0) {
            IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.CREATE_ACCOUNT_URL, paramMap);
            if (!iovResponse.getFlag()) //失败
                return result.error(iovResponse.getCode(), iovResponse.getMessage());

            return result.success(iovResponse.getMessage(), iovResponse.getFlag());
        }
        return result.error("失败", Boolean.FALSE);
    }

    /**
     * 车辆网编辑用户接口
     *
     * @param account
     * @return
     */
    @Override
    public ResponseResult<Boolean> modifyAccount(IovModifyAccountDto account) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (account == null)
            return result.error("参数不能为空", Boolean.FALSE);

        Map<String, Object> paramMap = MapObjectConvertUtil.objectToMap(account);
        if (paramMap != null && paramMap.size() > 0) {
            IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.MODIFY_ACCOUNT_URL, paramMap);
            if (!iovResponse.getFlag()) //失败
                return result.error(iovResponse.getCode(), iovResponse.getMessage());

            return result.success(iovResponse.getMessage(), iovResponse.getFlag());
        }
        return null;
    }

    /**
     * 车辆网修改密码接口
     *
     * @param account
     * @return
     */
    @Override
    public ResponseResult<Boolean> modifyPassword(String account, String password) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (StringUtil.isEmpty(account))
            return result.error("用户名不能为空", Boolean.FALSE);
        if (StringUtil.isEmpty(password))
            return result.error("密码不能为空", Boolean.FALSE);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("account", account);
        paramMap.put("password", password);

        IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.MODIFY_PASSWORD_URL, paramMap);
        if (!iovResponse.getFlag()) //失败
            return result.error(iovResponse.getCode(), iovResponse.getMessage());

        return result.success(iovResponse.getMessage(), iovResponse.getFlag());
    }

    /**
     * 获取用户角色信息
     *
     * @param account
     * @return
     */
    @Override
    public ResponseResult<List<IovGroupDto>> getAccountGroupByAccount(String account) throws Exception {
        ResponseResult<List<IovGroupDto>> result = new ResponseResult<List<IovGroupDto>>();
        if (StringUtil.isEmpty(account))
            return result.error("用户名不能为空");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("account", account);

        List<IovGroupDto> dataList = null;
        IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.GET_ACCOUNT_GROUP_URL, paramMap);
        if (!iovResponse.getFlag()) //失败
            return result.error(iovResponse.getCode(), iovResponse.getMessage());

        if (!StringUtil.isEmpty(iovResponse.getData())) {
            JSONObject iovRespJson = JSONObject.parseObject(iovResponse.getData());
            int selectedRoleId = iovRespJson.getIntValue("roleId");

            dataList = JSONObject.parseArray(iovRespJson.getString("roles"), IovGroupDto.class);
            dataList.forEach(data -> {
                if (data.getRoleId() == selectedRoleId)
                    data.setSelected(true);
            });
        }

        return result.success(iovResponse.getMessage(), dataList);
    }

    /**
     * 分页查询车联角色
     *
     * @return
     */
    @Override
    public ResponseResult<Paged<IovGroupDto>> getGroupListByPage(Map<String, Object> paramMap, int pageNum, int pageSize) throws Exception {
        ResponseResult<Paged<IovGroupDto>> result = new ResponseResult<Paged<IovGroupDto>>();
        IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.GET_GROUP_PAGE_LIST_URL, paramMap);
        if (!iovResponse.getFlag()) //失败
            return result.error(iovResponse.getCode(), iovResponse.getMessage());

        Paged<IovGroupDto> paged = new Paged<>();
        if (!StringUtil.isEmpty(iovResponse.getData())) {
            JSONObject iovRespJson = JSONObject.parseObject(iovResponse.getData());
            int total = iovRespJson.getIntValue("total");

            List<IovGroupDto> dataList = JSONObject.parseArray(iovRespJson.getString("records"), IovGroupDto.class);
            paged.setTotal(total);
            paged.setList(dataList);

            return result.success(iovResponse.getMessage(), paged);
        }
        return result.error(iovResponse.getCode(), iovResponse.getMessage());
    }

    /**
     * 查询车联网角色数量
     *
     * @return
     */
    @Override
    public ResponseResult<Integer> getGroupCount() throws Exception {
        ResponseResult<Integer> result = new ResponseResult<Integer>();
        IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.GET_GROUP_COUNT_URL, null);
        if (!iovResponse.getFlag()) //失败
            return result.error(iovResponse.getCode(), iovResponse.getMessage());

        if (!StringUtil.isEmpty(iovResponse.getData())) {
            return result.success(iovResponse.getMessage(), Integer.valueOf(iovResponse.getData()));
        }
        return result.error(iovResponse.getCode(), iovResponse.getMessage());
    }

    /**
     * 获取角色绑定的权限列表
     *
     * @return
     */
    @Override
    public ResponseResult<IovGroupBindResourceDto> getGroupPermission(int groupId) throws Exception {
        ResponseResult<IovGroupBindResourceDto> result = new ResponseResult<IovGroupBindResourceDto>();
        if (groupId <= 0)
            return result.error("角色id不能为空");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("roleId", groupId);

        IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.GET_GROUP_PERMISSION_URL, paramMap);
        if (!iovResponse.getFlag()) //失败
            return result.error(iovResponse.getCode(), iovResponse.getMessage());

        IovGroupBindResourceDto dto = new IovGroupBindResourceDto();
        if (!StringUtil.isEmpty(iovResponse.getData())) {
            JSONObject dataJson = JSONObject.parseObject(iovResponse.getData()); //返回的数据
            List<IovResourceDto> iovResourceDtos = JSONObject.parseArray(dataJson.getString("permissions"), IovResourceDto.class); //权限列表
            dto.setPermissionTree(iovResourceDtos);

            List<Integer> bindResourceIds = JSONObject.parseArray(dataJson.getString("rolePermissions"), Integer.class); //角色绑定的权限id8
            dto.setGroupBindpermissionIds(bindResourceIds);
            return result.success(iovResponse.getMessage(), dto);
        }
        return result.error(iovResponse.getCode(), iovResponse.getMessage());
    }

    /**
     * 添加角色
     *
     * @return
     */
    @Override
    public ResponseResult<Boolean> createGroup(IovCreateGroupDto group) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (group == null)
            return result.error("参数不能为空", Boolean.FALSE);

        Map<String, Object> paramMap = MapObjectConvertUtil.objectToMap(group);
        if (paramMap != null && paramMap.size() > 0) {
            IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.CREATE_GROUP_URL, paramMap);

            if (!iovResponse.getFlag()) //失败
                return result.error(iovResponse.getCode(), iovResponse.getMessage());

            return result.success(iovResponse.getMessage(), iovResponse.getFlag());
        }
        return result.error("失败", Boolean.FALSE);
    }

    /**
     * 修改角色
     *
     * @return
     */
    @Override
    public ResponseResult<Boolean> modifyGroup(IovModifyGroupDto group) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (group == null)
            return result.error("参数不能为空", Boolean.FALSE);
        if (group.getRoleId() <= 0)
            return result.error("id不能为空", Boolean.FALSE);

        Map<String, Object> paramMap = MapObjectConvertUtil.objectToMap(group);
        if (paramMap != null && paramMap.size() > 0) {
            IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.MODIFY_GROUP_URL, paramMap);

            if (!iovResponse.getFlag()) //失败
                return result.error(iovResponse.getCode(), iovResponse.getMessage());

            return result.success(iovResponse.getMessage(), iovResponse.getFlag());
        }
        return result.error("失败", Boolean.FALSE);
    }

    /**
     * 添加权限
     *
     * @param roleId        角色id
     * @param permissionIds 权限id集合
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult<Boolean> setPermission(int roleId, List<Integer> permissionIds) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (roleId <= 0)
            return result.error("角色id不能为空", Boolean.FALSE);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("permissionIds", permissionIds);
        paramMap.put("roleId", roleId);

        if (paramMap != null && paramMap.size() > 0) {
            IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.SET_PERMISSION_URL, paramMap);

            if (!iovResponse.getFlag()) //失败
                return result.error(iovResponse.getCode(), iovResponse.getMessage());

            return result.success(iovResponse.getMessage(), iovResponse.getFlag());
        }
        return result.error("失败", Boolean.FALSE);
    }

    /**
     * 获取角色
     *
     * @return
     */
    @Override
    public ResponseResult<List<IovGroupDto>> getGroupList() throws Exception {
        ResponseResult<List<IovGroupDto>> result = new ResponseResult<List<IovGroupDto>>();
        IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.GET_GROUP_LIST, null);
        if (!iovResponse.getFlag()) //失败
            return result.error(iovResponse.getCode(), iovResponse.getMessage());

        if (!StringUtil.isEmpty(iovResponse.getData())) {
            List<IovGroupDto> dataList = JSONObject.parseArray(iovResponse.getData(), IovGroupDto.class);
            return result.success(iovResponse.getMessage(), dataList);
        }
        return result.success(iovResponse.getMessage(), null);
    }

    @Override
    public List<IovAccountDto> getAccountList(List<String> accountList) throws Exception {
        List<IovAccountDto> dataList = null;
        if (CollectionUtils.isNotEmpty(accountList)) {
            Map<String, Object> param = new HashMap<>();
            param.put("emails", accountList);
            param.put("pageNum", 1);
            param.put("pageSize", accountList.size());

            IovResponseDto iovResponse = iovUtils.doPost(IovPropertyUtils.GET_USER_LIST, param);
            if (!iovResponse.getFlag() || iovResponse.getCode() != ResponseCodeEnum.SUCCESS.getCode()) { //失败
                throw new BizException(iovResponse.getCode(), iovResponse.getMessage());
            }

            if (!StringUtil.isEmpty(iovResponse.getData())) {
                JSONObject dataObj = JSONObject.parseObject(iovResponse.getData());
                if (dataObj.getInteger("total") > 0) {
                    dataList = JSONObject.parseArray(dataObj.getString("records"), IovAccountDto.class);
                }
            }
        }
        return dataList;
    }
}
